package com.txby.alipay;


import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayDataDataserviceBillDownloadurlQueryModel;
import com.alipay.api.domain.AlipayTradeCancelModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

/**
 * 支付宝交易处理
 * 
 * @ClassName: AlipayTradeUtil
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author jacking
 * @date 2017年10月30日 下午4:33:40
 *
 */
public class AlipayTradeUtilTest {
 
	/**
	 * 交易取消
	* @Title: alipayTradeCancel 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param ac
	* @param @param outTradeNo
	* @param @return    设定文件 
	* @return JSONObject    返回类型 
	* @throws
	 */
	public JSONObject alipayTradeCancel(AlipayConfig ac,String outTradeNo) {
		JSONObject json = null;
		try {
			AlipayClient alipayClient = new DefaultAlipayClient(ac.gatewayUrl, ac.app_id,
					ac.merchant_private_key, ac.format, ac.charset,
					ac.alipay_public_key, ac.sign_type);
			AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
			AlipayTradeCancelModel model = new AlipayTradeCancelModel();
			model.setOutTradeNo(outTradeNo);
			request.setBizModel(model);
			AlipayTradeCancelResponse response = alipayClient.execute(request);
			if(response.isSuccess()){
//				System.out.println("调用成功");
				json = JSON.parseObject(response.getBody());
			} else {
//				System.out.println("调用失败");
			} 
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return null;
		}
		return json;
	}
	/**
	(查询对账单下载地址)
	* @Title: alipayDataDataserviceBillDownloadurlQuery 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param ac
	* @param @param billDate 账单时间：日账单格式为yyyy-MM-dd，月账单格式为yyyy-MM。
	* @param @return    设定文件 
	* @return JSONObject    返回类型 
	* @throws
	 */
	public  JSONObject alipayDataDataserviceBillDownloadurlQuery(AlipayConfig ac,String billDate)  {
		JSONObject json = null;
		try {
			
			AlipayClient alipayClient = new DefaultAlipayClient(ac.gatewayUrl, ac.app_id, ac.merchant_private_key, ac.format, ac.charset, ac.alipay_public_key, ac.sign_type);
			AlipayDataDataserviceBillDownloadurlQueryRequest request = 	new AlipayDataDataserviceBillDownloadurlQueryRequest();
			AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
			//账单时间：日账单格式为yyyy-MM-dd，月账单格式为yyyy-MM。
			model.setBillDate("2017-11");
			//账单类型，trade指商户基于支付宝交易收单的业务账单；signcustomer是指基于商户支付宝余额收入及支出等资金变动的帐务账单；
			model.setBillType("trade");
			request.setBizModel(model);
			AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
		 	if(response.isSuccess()){
//				System.out.println("调用成功");
				json = JSON.parseObject(response.getBody());
			} else {
//				System.out.println("调用失败");
			} 
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return json;
	}
	/**
	(统一收单交易退款接口)
	* @Title: alipayTradeRefund 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param  ac
	* @param outTradeNo 传入的商户订单号
	* @param refundAmount  需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
	* @return JSONObject    返回类型 
	* @throws
	 */
	public  JSONObject alipayTradeRefund(AlipayConfig ac,String outTradeNo, String refundAmount)  {
		JSONObject json = null;
		try {
			AlipayClient alipayClient = new DefaultAlipayClient(ac.gatewayUrl, ac.app_id, ac.merchant_private_key, ac.format, ac.charset, ac.alipay_public_key, ac.sign_type);
			AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
			AlipayTradeRefundModel model = new AlipayTradeRefundModel();
			//外部订单号
			model.setOutTradeNo(outTradeNo);
			//退款金额
			model.setRefundAmount(refundAmount);
			//标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传。
			//model.setOutRequestNo("HZ01RF001");
			request.setBizModel(model);
			AlipayTradeRefundResponse response = alipayClient.execute(request);
			json = JSON.parseObject(response.getBody());
	/*		if(response.isSuccess()){
//				System.out.println("调用成功");
				json = JSON.parseObject(response.getBody());
			} else {
//				System.out.println("调用失败");
			} */
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return json;
	}
	
	/**
	商家扫码收钱
	统一收单交易支付接口（条码支付）
	* @Title: alipayTradeRefund 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param ac
	* @param @param outTradeNo  传入的商户订单号
	* @param @param totalAmount 金额
	* @param @param authCode 支付授权码，25~30开头的长度为16~24位的数字，实际字符串长度以开发者获取的付款码长度为准
	* @param @param subject 订单标题
	* @param @return    设定文件 
	* @return JSONObject    返回类型 
	* @throws
	 */
	public  JSONObject alipayTradePay(AlipayConfig ac,String outTradeNo, String totalAmount,String authCode,String subject)  {
		JSONObject json = null;
		try {
	        //获得初始化的AlipayClient
				AlipayClient alipayClient = new DefaultAlipayClient(ac.gatewayUrl, ac.app_id, ac.merchant_private_key, ac.format, ac.charset, ac.alipay_public_key, ac.sign_type);
				//创建API对应的request类		
				AlipayTradePayRequest request = new AlipayTradePayRequest(); //创建API对应的request类 
				AlipayTradePayModel model = new AlipayTradePayModel();
				model.setOutTradeNo(outTradeNo);
				model.setScene("bar_code");
				//支付授权码，25~30开头的长度为16~24位的数字，实际字符串长度以开发者获取的付款码长度为准
				model.setAuthCode(authCode);
				//订单标题
				model.setSubject(subject);
				model.setTotalAmount(totalAmount);
				request.setBizModel(model);
//		         下面两代码是使用第三方应用授权传值方式
				/****************************授权传app_auth_token写法*********************
			
		          第三方应用授权获取app_auth_token可参照该贴：https://openclub.alipay.com/read.php?tid=1649&fid=43
		          获取app_auth_token
		          String app_auth_token="";
		          AlipayTradePayResponse response = alipayClient.execute(request,"",app_auth_token);
		      	 **/
			//通过alipayClient调用API，获得对应的response类			
			AlipayTradePayResponse response = alipayClient.execute(request);
			json = JSON.parseObject(response.getBody());
	/*		if(response.isSuccess()){
//				System.out.println("调用成功");
				json = JSON.parseObject(response.getBody());
			} else {
//				System.out.println("调用失败");
			} */
//			 System.out.println("地址：" + response.getBody());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return json;
	}
	 /**
	                用户二维码扫描支付
	  * alipay.trade.precreate (统一收单线下交易预创建)
	 * @Title: alipayTradePrecreate 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param @param ac
	* @param @param outTradeNo  传入的商户订单号 out_trade_no（订单号）必须是唯一的，测试一次必须修改新的订单号
	* @param @param totalAmount 金额
	* @param @param subject 订单标题
	 * @param @return    设定文件 
	 * @return JSONObject    返回类型 
	 * @throws
	  */
	public  JSONObject alipayTradePrecreate(AlipayConfig ac,String outTradeNo, String totalAmount,String subject)  {
		JSONObject json = null;
		try {
			AlipayClient alipayClient = new DefaultAlipayClient(ac.gatewayUrl, ac.app_id, ac.merchant_private_key, ac.format, ac.charset, ac.alipay_public_key, ac.sign_type);
			AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
			AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
			//out_trade_no（订单号）必须是唯一的，测试一次必须修改新的订单号
			model.setOutTradeNo(outTradeNo);
			model.setTotalAmount(totalAmount);
			model.setSubject(subject);
			request.setBizModel(model);
			AlipayTradePrecreateResponse response =  alipayClient.execute(request);
			//条码支付详细信息
			//qr_Code当前预下单请求生成的二维码码串，可以用二维码生成工具根据该码串值生成对应的二维码
			json = JSON.parseObject(response.getBody());
	/*		if(response.isSuccess()){
				System.out.println("条码支付详细信息："+response.getBody());
				System.out.println("二维码码串："+response.getQrCode());
				json = JSON.parseObject(response.getBody());
			} else {
//				System.out.println("调用失败");
			} */
//			 System.out.println("地址：" + response.getBody());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return json;
	}
	/**
	alipay.trade.query (统一收单线下交易查询)
	 * 
	* @Title: alipayTradeQuery 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param ac
	 @param @param outTradeNo  传入的商户订单号 out_trade_no（订单号）必须是唯一的，测试一次必须修改新的订单号
	* @param @return    设定文件 
	* @return JSONObject    返回类型 
	* @throws
	 */
	public  JSONObject alipayTradeQuery(AlipayConfig ac,String outTradeNo)  {
		JSONObject json = null;
		try {
			AlipayClient alipayClient = new DefaultAlipayClient(ac.gatewayUrl, ac.app_id, ac.merchant_private_key, ac.format, ac.charset, ac.alipay_public_key, ac.sign_type);
			AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
			//out_trade_no（外部订单号）和trade_no（支付宝交易号)二选一用 即可查询
			AlipayTradeQueryModel model = new AlipayTradeQueryModel();
			model.setOutTradeNo(outTradeNo);
			//model.setTradeNo("2016113021001004950297103440");
			request.setBizModel(model);
			AlipayTradeQueryResponse response = alipayClient.execute(request);
			System.out.println(response.getBody());
			json = JSON.parseObject(response.getBody());
		/*	if(response.isSuccess()){
				json = JSON.parseObject(response.getBody());
			} else {
//				System.out.println("调用失败");
			} */
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return json;
	}
	public static void main(String[] args) {
		AlipayTradeUtilTest at=new AlipayTradeUtilTest();
		AlipayConfig ac=new  AlipayConfig();
/*		String outTradeNo=System.currentTimeMillis()+"";
		  System.out.println("订单号："+outTradeNo);
		  JSONObject jo=  at.alipayTradePrecreate(ac, outTradeNo, "1", "华硕电脑");
		  jo=jo.getJSONObject("alipay_trade_precreate_response");
		System.out.println("支付二维码:"+jo.get("qr_code"));*/
	
		System.out.println(	at.alipayTradeQuery(ac, "1510645332218"));
//		
//		System.out.println(	at.alipayTradeRefund(ac, "1510643644220", "1"));
		
		Map wxm=new HashMap();
	 	wxm.put("certPath", "D:/txbyCert/wxRefundApiclient_cert.p12");
	 	wxm.put("app_id", "wxd655b5106a5c43a2");
	 	wxm.put("mch_id", "1387070702");
	 	wxm.put("key", "A0F9B00D126D486D28AA9A0F6FC8F88C");
	 	wxm.put("notify_url", "http://api.eeesys.com/shopOrder/wxpay/notify");
	 	System.out.println(JSON.toJSON(wxm));
	 	wxm.clear();
	 	
	 	 String merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDCDsISX2QyY7Jq" + 
	 			"AJxnHFitvJFRUnBvIq4+O3MoGA9iPY06XkIn8dKwkXPW4NX5hJvTfGV3LZWQVs6s" + 
	 			"K2UcEN2GZjyW956QBGM8v3+EI9dNeJXZp+ufIlwX1KP6pVJhLURp0ZC3e8G2+rYZ" + 
	 			"voBL+zHjz5WPK4BQA0R/G4V879WA5vT6Y/Hy3uFbCFfW8pTzCKacwTgxOmALrvlW" + 
	 			"IuDEXk7HuuTTTmTzUK8PJtqiVsAwWgNoijrDMgzU4rwjQ0IPxw9PYwcWXbLXwdp/" + 
	 			"DcPXX7AUKHxyT4KVG8/9HnXmojzrbWrgtQuvBV6ZVsx9+/+8hku2p4L/jFxKhR9Y" + 
	 			"YA0ZrAcJAgMBAAECggEAKkTSqvPSPFOQ8hvt9VusSTOQp5kAWoTAVVfXrn0HJMvp" + 
	 			"bjRHzrGSxdj41W4lzXLACmHHLB1mvYja/Y96N5HI3tR4EB4hkJcUEpBXsy2nYP2K" + 
	 			"Dl3QKdp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hW4Q5H7bepZkMzpCUTqyk75Y2YVije2aEONGQJCziufjcilOXjO236ofFj5UxAJb" + 
	 			"hluOwQI3BijosrWdy0pZpnPmvobm9YFiVQuwBCU8lGqkHB825vN1Y1JhQGmQDsB0" + 
	 			"Z9bPpmtIY8VGDY2B6BoM63Y=";
	 	 
	 	String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAggi9kx0b0zpGQ6yP7c4M3a49yUouZ4Z+8gzRvljT2IO9CylX+0VWTU9Mbmcm5WSbvYPki2fRI/crWsnX5QxV3y05q5dW6XhYR2QWwc7gsOsLxFcWpLwJLQtrpqYPKMS7siasQ26W8cpEbKN+0FYlZi0Xw+I3uL87+s6fYZwhye5kQfKsyGw/gHmmEzmstEFdU7pzEJ4w5Zl9SnW35piYCbLaQ+S2RKzaw0UX7hfdpJPO9RUsgahoBM3stZgyxayjGcismGC3ss+TVLrGHhkedKTIRKAbCkLm16RbeAHMqSOJqBwbEyUM0EyiD9pT/uBmfS0gTnGpOjLepDlH6Wp6ZwIDAQAB";
	 	
	 	wxm.put("app_id", "2017111309908295");
	 	wxm.put("merchant_private_key", merchant_private_key);
	 	wxm.put("alipay_public_key", alipay_public_key);
	 	wxm.put("gatewayUrl", "https://openapi.alipay.com/gateway.do");
	 	wxm.put("notify_url", "http://api.eeesys.com/shopOrder/alipay/notify");
	 	System.out.println(JSON.toJSON(wxm));
		
		
	}

}
